package user

import (
	"enjoy_xxz/base"
	"enjoy_xxz/formdata"
	"enjoy_xxz/internal/model/database/redis"
	"enjoy_xxz/internal/server/user"
	"enjoy_xxz/pkg"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"time"
)

// 用户登录
func Login(c *gin.Context) {
	var data formdata.UserLogin
	if err := c.ShouldBindJSON(&data); err != nil {
		base.RespData(c, nil, err)
		return
	}
	fmt.Println("登录方式", data.LoginType)
	login, err := user.Login(data)
	if err != nil {
		base.RespData(c, login, err)
		return
	}
	//储存token
	key := "phone_" + data.Phone
	err = redis.SetRedisVal(key, login.Token, time.Minute*5)
	base.RespData(c, login, err)
}

// 微信token
func WeiXinToken() {

}

// 用户注册
func Register(c *gin.Context) {
	var data formdata.UserRegister
	if err := c.ShouldBindJSON(&data); err != nil {
		base.RespData(c, nil, err)
		return
	}
	token, err := user.Register(data)
	base.RespData(c, token, err)
}

// 修改用户密码
func UpdatePasswordByUserID(c *gin.Context) {
	var data formdata.UpdateDara
	if err := c.ShouldBindJSON(&data); err != nil {
		base.RespData(c, nil, err)
		return
	}
	userID := pkg.GetAutoUserID(c)
	err := user.UpdatePasswordByUserID(data, userID)
	base.RespData(c, "", err)
}

// 发送短信
func SendCode(c *gin.Context) {
	var data formdata.SendCode
	if err := c.ShouldBindJSON(&data); err != nil {
		base.RespData(c, nil, err)
		return
	}
	fmt.Println("短信验证码类型", data.CodeType)
	//手机号格式效验
	bools := pkg.MobileTypeBook(data.Phone)
	if !bools {
		base.RespData(c, "", errors.New("手机号格式效验错误"))
		return
	}
	//生成验证码
	code := pkg.NumCodeString()
	//发短信
	err := pkg.SendCode(data.Phone, code)
	if err != nil {
		fmt.Println("短信错误消息》》", err)
		return
	}
	//储存短信验证码
	key := "phone_:" + data.Phone + "_type" + data.CodeType
	err = redis.SetRedisVal(key, code, time.Minute*30)
	base.RespData(c, nil, err)
}
